<template>
  <el-header height="70px" v-loading="loading">
    <el-row :gutter="20" type="flex">
      <el-col :span="3">
        <img src="../assets/icon.png" alt="" height="60%" style="padding-top: 9%">
      </el-col>
      <el-col :span="13">
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
          <el-menu-item index="1" style="font-size: large" @click="goToDashboard()">首页</el-menu-item>
          <el-menu-item index="3" style="font-size: large" @click="openRelease()">发帖</el-menu-item>
          <el-menu-item index="4" style="font-size: large">排行榜</el-menu-item>
        </el-menu>
      </el-col>
      <el-col :span="4">
        <el-input
          placeholder="请输入内容"
          prefix-icon="el-icon-search"
        >
          <el-button
            style="padding-right:10px"
            slot="suffix"
            type="text"
          >搜索
          </el-button
          >
        </el-input>
      </el-col
      >
      <el-col :span="4">
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect" v-if="this.$store.getters.getUser === null">
          <el-menu-item index="1" style="font-size: large" @click="dialogFormVisible = true">登录</el-menu-item>
          <el-menu-item index="3" style="font-size: large" @click="dialogFormVisible2 = true">注册</el-menu-item>
        </el-menu>
        <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect" v-else>
            <el-menu-item index="1" style="font-size: large" @click="goToUserInfo()">{{ this.$store.getters.getUser.UID }}</el-menu-item>
            <el-menu-item index="3" style="font-size: large" @click="logout()">注销</el-menu-item>
        </el-menu>
      </el-col>
    </el-row>
    <el-dialog title="登录" :visible.sync="dialogFormVisible" center width="500px">
      <el-form :model="form" ref="form">
        <el-form-item label="账号" prop="username" :label-width="formLabelWidth" :rules="[{ required: true, message: '请输入用户名', trigger: ['blur', 'change'] }]">
          <el-input v-model="form.username" autocomplete="off"
                    placeholder="请输入用户名"
                    prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth" :rules="[{ required: true, message: '请输入密码', trigger: ['blur', 'change'] }]">
          <el-input v-model="form.password" autocomplete="off"
                    placeholder="请输入密码"
                    prefix-icon="el-icon-lock"
                    show-password></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="login('form')">登 录</el-button>
      </div>
    </el-dialog>

    <el-dialog title="注册" :visible.sync="dialogFormVisible2" center width="500px">
      <el-form :model="form2" ref="form2">
        <el-form-item label="账号" prop="username" :label-width="formLabelWidth" :rules="[{ required: true, message: '请输入用户名', trigger: ['blur', 'change']}, {pattern: /^[a-zA-Z0-9_]+$/, message: '用户名需要英文或数字', trigger: ['blur', 'change']}]">
          <el-input v-model="form2.username" autocomplete="off"
                    placeholder="请输入用户名"
                    prefix-icon="el-icon-user"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password" :label-width="formLabelWidth" :rules="[{ required: true, message: '请输入密码', trigger: ['blur', 'change']},{pattern: /^[A-Za-z0-9]{6,20}$/, message: '密码长度为6-20', trigger: ['blur', 'change']}]">
          <el-input v-model="form2.password" autocomplete="off"
                    placeholder="请输入密码"
                    prefix-icon="el-icon-lock"
                    show-password></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email" :label-width="formLabelWidth" :rules="[{required: true, message: '请输入邮箱', trigger: ['blur', 'change']}, {pattern: /^[a-z0-9A-Z]+[- | a-z0-9A-Z . _]+@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-z]{2,}$/, message: '请输入正确的邮箱', trigger: ['blur', 'change']}]">
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-message"
            v-model="form2.email"
            autocomplete="off"
          >
            <el-button
              style="padding-right:10px"
              slot="suffix"
              type="text"
              v-if="is_code===false"
              @click="getCode()"
            >获取验证码
            </el-button
            >

            <el-button
              style="padding-right:10px"
              slot="suffix"
              type="text"
              v-else
            >已发送验证码
            </el-button
            >
          </el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code" :label-width="formLabelWidth" :rules="[{ required: true, message: '请输入验证码', trigger: ['blur', 'change'] }]">
          <el-input v-model="form2.code" autocomplete="off"
                    placeholder="请输入验证码"
                    prefix-icon="el-icon-lock"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="register('form2')">注 册</el-button>
      </div>
    </el-dialog>

    <el-dialog title="发帖" :visible.sync="dialogFormVisible3" center width="500px">
      <el-form :model="form3" ref="form3">
        <el-form-item label="标题" prop="title" :label-width="formLabelWidth" :rules="[{ required: true, message: '请输入标题', trigger: ['blur', 'change'] }]">
          <el-input v-model="form3.title" autocomplete="off"
                                placeholder="请输入标题"
                                prefix-icon="el-icon-user"
        ></el-input>
        </el-form-item>
        <el-form-item label="内容" prop="content" :label-width="formLabelWidth" :rules="[{required:true, message: '请输入内容', trigger: ['blur', 'change']}]">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="请输入内容"
            v-model="form3.content">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible3 = false">取 消</el-button>
        <el-button type="primary" @click="release('form3')">发表</el-button>
      </div>
    </el-dialog>
  </el-header>
</template>

<script>

export default {
  name: 'header',
  mounted () {
    console.log(this.$store.getters.getUser)
  },
  data () {
    return {
      activeIndex: '1',
      activeIndex2: '1',
      dialogFormVisible: false,
      dialogFormVisible2: false,
      dialogFormVisible3: false,
      form: {
        username: '',
        password: ''
      },
      form2: {
        username: '',
        password: '',
        email: '',
        code: ''
      },
      form3: {
        authorId: this.UID,
        title: '',
        content: '',
        categoryId: 1
      },
      formLabelWidth: '15%',
      UID: '',
      loading: false,
      is_code: false,
      code: 60,
      show: true,
      count: '',
      timer: null
    }
  },
  methods: {
    handleSelect (key, keyPath) {
      console.log(key, keyPath)
    },
    login (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const _this = this
          this.$axios.post('/login', this.form).then(res => {
            const jwt = res.headers['authorization']
            const userInfo = res.data.data
            _this.$store.commit('SET_TOKEN', jwt)
            _this.$store.commit('SET_USERINFO', userInfo)
            this.UID = userInfo.UID
            this.dialogFormVisible = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    testSpace () {
      var reg = /^[/u4E00/-/u9FA5]+$/
      let str = this.form2.username
      if (reg.test(str)) {
        console.log(str)
        this.form2.username = str.replace(/\s/g, '')
      } else {
        this.form2.username = str.replace(/(^\s*)|(\s*$)/g, '')
      }
    },
    goToUserInfo () {
      console.log(this.$store.getters.getUser.UID)
      const _this = this
      // eslint-disable-next-line standard/object-curly-even-spacing
      // eslint-disable-next-line standard/object-curly-even-spacing
      if (_this.$store.getters.getUser.role === 1) {
        _this.$router.push({name: 'adminDashboard',
          params: {
            UID: _this.$store.getters.getUser.UID
          }})
      } else {
        // this.$message({
        //   message: '验证失败',
        //   type: 'error'
        // })
        _this.$router.push('/userinfo')
      }
    },
    goToDashboard () {
      const _this = this
      _this.$router.push('/')
    },
    logout () {
      const _this = this
      _this.$axios.get('/logout').then(res => {
        _this.$router.push('/')
        console.log('=============')
        console.log('success logout!')
        console.log('=============')
        _this.$store.commit('REMOVE_INFO')
        this.UID = ''
        this.$router.go(0)
        this.$message({
          message: '注销成功!',
          type: 'success'
        })
      })
    },
    sleep (time) {
      return new Promise((resolve) => setTimeout(resolve, time))
    },
    getCode () {
      if (this.form2.email !== '') {
        console.log('/register/send?goal=' + this.form2.email)
        this.is_code = true
        this.$axios.get('/register/send?goal=' + this.form2.email)
      } else {
        this.$message({
          message: '请输入邮箱！',
          type: 'error'
        })
      }
      // const TIME_COUNT = 60
      // if (!this.timer) {
      //   this.count = TIME_COUNT
      //   this.show = false
      //   this.timer = setInterval(() => {
      //     if (this.count > 0 && this.count <= TIME_COUNT) {
      //       this.count--
      //       console.log(this.count)
      //     } else {
      //       this.show = true
      //       clearInterval(this.timer)
      //       this.timer = null
      //     }
      //   }, 1000)
      // }
      // this.is_code = false
    },
    register (formName) {
      this.$refs[formName].validate((valid) => {
        console.log('********')
        console.log(this.form3)
        console.log('********')
        if (valid) {
          const _this = this
          _this.$axios.post('/register', this.form2)
          this.dialogFormVisible2 = false
          this.$message({
            message: '注册成功',
            type: 'success'
          })
        } else {
          console.log('error submit!!')
          this.$message({
            message: '验证失败！',
            type: 'error'
          })
          return false
        }
      })
    },
    openRelease () {
      if (this.$store.getters.getUser.UID === '') {
        this.$message({
          showClose: true,
          message: '请先登录',
          type: 'error'
        })
        this.dialogFormVisible = 1
      } else {
        const _this = this
        _this.dialogFormVisible3 = 1
      }
    },
    release (formName) {
      this.form3.authorId = this.$store.getters.getUser.UID
      this.$refs[formName].validate((valid) => {
        const _this = this
        this.dialogFormVisible3 = false
        _this.$axios.post('/post/release', this.form3).then(res => {
          _this.$message({
            showClose: true,
            message: '发送成功',
            type: 'success'
          })
          console.log('发送成功!')
        })
      })
    }
  }
}
</script>

<style scoped>
.el-header, .el-menu {
  background-color: #dde9f6;
  color: #333;
  text-align: center;
  line-height: 10%;
  font-size: larger;
}

.el-menu-item, .el-tem, .el-col, .el-col {
  height: 70px;
  vertical-align: center;
  text-align: center;
  line-height: 70px;
}
html, body, #app, .el-container {
  padding: 0;
  margin: 0;
  height: 100%;
}

.text {
  font-size: 20px;
}

.item {
  padding: 8px 0;
  height: 50px;
  font-size: larger;
}

.box-card {
  height: 600px;
  margin-left: 20px;
  margin-top: 50px;
}

.box-card1 {
  margin-left: 80px;
}

.box-card2 {
  margin-right: 80px;
}

.el-menu-item {
  font-size: larger;
}
</style>
